<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <title>表单提交事件练习</title>
    <script>

      function check(username, password, confirmPwd, email) {
        if (username == "" || password == "" || confirmPwd == "" || email == "") {
          alert("请检查表单，有未填项");
          return false;
        }
        if (username.length > 6 || username.length < 4) {
          alert("用户名长度有误(4-6)");
          return false;
        }
        if (password.length !== 6) {
          alert("密码长度有误(6)");
          return false;
        }
        if (!(confirmPwd === password)) {
          alert("请重新确认密码");
          return false;
        }

        //如何在js中使用正则表达式
        //在java中，转义符是\\, 在js中使用正则表达式 \
        //emailPattern.test("xxx"), 验证"xxx"是不是满足emailPattern规则
        //   如果满足返回true, 否则返回false
        var emailPattern = /^[\w-]+@([a-zA-Z]+\.)+[a-zA-Z]+$/;
        if(!emailPattern.test(email)) {
          alert("电子邮件格式不正确");
          return false;
        }
        return true;
      }
      //动态注册表单提交事件
      window.onload = function () {
        //拿到form表单 dom对象
        var form = document.getElementById("form");
        form.onsubmit = function () {
          var username = form.username.value;
          var password = form.password.value;
          var confirmPwd = form.confirmPwd.value;
          var email = form.email.value;
          if (!check(username, password, confirmPwd, email)) {
            return false;
          }
          return true;
        }
      }
    </script>
  </head>

  <body>
    <h1>注册用户</h1>
    <form action="ok.html" id="form" method="post">
      用户名：<input type="text" id="username" name="username">长度(4-6)<br/>
      密 码：<input type="text" id="password" name="password">长度(6)<br/>
      确 认：<input type="text" id="confirmPwd" name="confirmPwd">长度(6)<br/>
      电 邮：<input type="text" id="email" name="email">满足基本格式<br/>
      <input type="submit" value="注册用户"/>
    </form>
  </body>
</html>